/**
 * Copyright (c) 2010 XXXXX
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ar.edu.itba.ia2010.geneticos.motor.api.corte;

import java.io.OutputStream;
import java.util.Formatter;
import java.util.Observable;
import java.util.Observer;

import org.apache.commons.lang.Validate;

import ar.edu.itba.ia2010.geneticos.motor.api.corte.EvolucionAptitudDecoratorEstrategiaCorte.AgeInformation;

/**
 * Imprime la informacion sobre cada iteracion
 * 
 * @author Juan F. Codagnone
 * @since Mar 23, 2010
 */
public class TSVOutputStreamObserver implements Observer {
    private final Formatter writer;
    private boolean header;
    private int age;
    private long t0 = System.currentTimeMillis();
    
    /**  Creates the TSVOutputStreamObserver. */
    public TSVOutputStreamObserver(final boolean header, 
            final OutputStream os) {
        Validate.notNull(os);
        
        this.header = header;
        this.writer = new Formatter(os);
    }
    
    /** @see Observer#update(Observable, Object) */
    public final void update(final Observable o, final Object arg) {
        if(header) {
            header = false;
            writer.format("age\ttime\tmin  \tmax   \tavg  \n");
        }
        final AgeInformation<Boolean> info = (AgeInformation) arg;
     
        final long t = System.currentTimeMillis();
        writer.format("%d\t%d\t%.4f\t%.4f\t%.4f\t%s\n", ++age, 
                 t - t0, info.getMin(), info.getMax(), 
                info.getAvg(), info.getApto()).flush();
        t0 = t;
    }

}
